<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Parent</title>
</head>

<body>
  <h1>Parent</h1>
  <button id="sendMessage">给iframe发消息</button>
  <iframe id="childFrame" src="son.html" width="600" height="400"></iframe>

  <script>
    const iframe = document.getElementById('childFrame');
    const sendMessageButton = document.getElementById('sendMessage');

    // 发送消息到 iframe
    sendMessageButton.addEventListener('click', () => {
      const message = { text: 'Hello World!' };
      iframe.contentWindow.postMessage(message, '*'); // 使用 '*' 作为目标域
    });

    // 监听来自 iframe 的消息
    window.addEventListener('message', (event) => {
      // 安全起见，检查 event.origin 消息来源
      console.log('接收iframe页的消息:', event.data);
    });
  </script>
</body>

</html>
